package cn.wikiflyer.beikang.view;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.wikiflyer.beikang.R;

/**
 * 
 * @author ZJJ
 * 
 */
public class AddAndSubView extends LinearLayout {
	private TextView addButton;
	private TextView subButton;
	private EditText editText;
	private int num;
	private Context context;
	private ICartUpdate cartUpdate;
	private String id;

	/**
	 * 设置更新监听器
	 */
	public void setCartUpdate(ICartUpdate c) {
		this.cartUpdate = c;
	}

	public void setId(String id) {
		this.id = id;
	}

	public AddAndSubView(Context context) {
		this(context, null);
	}

	public AddAndSubView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		num = 0;
		addView(View.inflate(context, R.layout.custom_add_sub_view, null));
		initView();
	}

	private void initView() {
		addButton = (TextView) findViewById(R.id.textView_add);
		subButton = (TextView) findViewById(R.id.textView_sub);
		editText = (EditText) findViewById(R.id.editText_num);

		addButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				num++;
				updateUI();
			}
		});
		subButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				num--;
				updateUI();
			}
		});
		editText.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			public void afterTextChanged(Editable s) {
				try {
					if (s == null || s.equals("")) {
						num = 0;
					} else {
						num = Integer.valueOf(s.toString());
					}
				} catch (Exception e) {
					e.printStackTrace();
					num = 0;
				}
				cartUpdate.updateCart(id, num);
			}
		});
	}

	public void updateUI() {
		
		if (num < 0) {
			num = 0;
		}
		editText.setText(num + "");
		cartUpdate.updateCart(id, num);
	}

	/**
	 * 设置editText中的值
	 */
	public void setNum(int num) {
		this.num = num;
//		updateUI();
		editText.setText(num+"");
	}

	/**
	 * 获取editText中的值
	 */
	public int getNum() {
		return num;
	}

	public interface ICartUpdate {
		public void updateCart(String id, int num);
	}
}
